package ioc

import (
	"JK-Junior-Go-Engineer-Camp/webook/internal/web"
	ijwt "JK-Junior-Go-Engineer-Camp/webook/internal/web/jwt"
	"JK-Junior-Go-Engineer-Camp/webook/internal/web/middleware"
	"JK-Junior-Go-Engineer-Camp/webook/pkg/ginx/middleware/ratelimit"
	"JK-Junior-Go-Engineer-Camp/webook/pkg/limiter"
	"JK-Junior-Go-Engineer-Camp/webook/pkg/logger"
	"context"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"strings"
	"time"
)

// InitWebServer 初始化web服务器
func InitWebServer(middlewares []gin.HandlerFunc,
	userHdl *web.UserHandler, wechatHdl *web.OAuth2WechatHandler,
	artHdl *web.ArticleHandler) *gin.Engine {
	server := gin.Default()
	server.Use(middlewares...)
	userHdl.RegisterRoutes(server)
	wechatHdl.RegisterRoutes(server)
	artHdl.RegisterRoutes(server)
	return server
}

// InitGinMiddlewares 初始化用到的Gin中间件
func InitGinMiddlewares(redisClient redis.Cmdable,
	hdl ijwt.Handler, l logger.LoggerV1) []gin.HandlerFunc {
	return []gin.HandlerFunc{
		// CORS 跨域问题
		cors.New(cors.Config{
			AllowCredentials: true,
			AllowHeaders:     []string{"content-type", "authorization"},
			ExposeHeaders:    []string{"x-jwt-token", "x-refresh-token"},
			AllowOriginFunc: func(origin string) bool {
				if strings.Contains(origin, "localhost") {
					return true
				}
				return strings.Contains(origin, "your_company.com")
			},
			MaxAge: 12 * time.Hour,
		}),
		// 限流
		ratelimit.NewBuilder(limiter.NewRedisSlidingWindowLimiter(redisClient,
			time.Second, 100)).Build(),
		// 日志
		middleware.NewLogMiddlewareBuilder(func(ctx context.Context, al middleware.AccessLog) {
			l.Debug("", logger.Field{Key: "access_log", Val: al})
		}).AllowReqBody().AllowRespBody().Build(),
		// JWT 鉴权
		middleware.NewLoginJWTMiddlewareBuilder(hdl).CheckLogin(),
	}
}
